package com.gasolinator.a;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.widget.Toast;
import com.gasolinator.a.app.GasolinatorStation;
import com.gasolinator.a.app.helper.GasolinatorPreferences;
import com.gasolinator.a.augmented_reality.activity.AugmentedReality;
import com.gasolinator.a.augmented_reality.data.ARData;
import com.gasolinator.a.augmented_reality.data.GasolinatorDataSource;
import com.gasolinator.a.augmented_reality.data.NetworkDataSource;
import com.gasolinator.a.augmented_reality.ui.GasolinatorMarker;
import com.gasolinator.a.augmented_reality.ui.Marker;
import com.gasolinator.a.bug.UncaughtExceptionHandler;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Locale;

public class GasWalkerActivity extends AugmentedReality {

    private static final String locale = Locale.getDefault().getLanguage();
    private static Collection<NetworkDataSource> sources = null;
    private static Thread thread = null;

    /**
     * {@inheritDoc}
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler(this));
        if (sources==null) {
            sources = new ArrayList<NetworkDataSource>();
            GasolinatorDataSource gasolinator = GasolinatorDataSource.getInstance(getApplicationContext());
            sources.add(gasolinator);
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        Location last = ARData.getCurrentLocation();
        updateData(last.getLatitude(),last.getLongitude(),last.getAltitude());
    }

    @Override
    protected void markerTouched(Marker marker) {
        GasolinatorMarker gasolinatorMarker = (GasolinatorMarker) marker;
        GasolinatorStation gasolinatorStation = gasolinatorMarker.getStation();
        String msg = getGasolinatorPriceTable(gasolinatorStation);
        Toast t = Toast.makeText(getApplicationContext(), msg.toString(), Toast.LENGTH_SHORT);
        t.setGravity(Gravity.CENTER, 0, 0);
        t.show();
    }

    private String getGasolinatorPriceTable(GasolinatorStation gasolinatorStation) {
        StringBuilder builder = new StringBuilder();
        builder.append(gasolinatorStation.getName()).append("\n");
        builder.append(gasolinatorStation.getAddress()).append("\n");
        builder.append("Gasoil  : ").append(gasolinatorStation.getPrice("gasoil")).append("€/L").append("\n");
        builder.append("Super 95: ").append(gasolinatorStation.getPrice("gas95")).append("€/L").append("\n");
        builder.append("Super 98: ").append(gasolinatorStation.getPrice("gas98")).append("€/L").append("\n");
        return builder.toString();
    }

    @Override
    public void onLocationChanged(Location location) {
        super.onLocationChanged(location);
        updateData(location.getLatitude(), location.getLongitude(), location.getAltitude());
    }

    private void updateData(final double lat, final double lon, final double alt) {
        if (thread!=null && thread.isAlive()) return;

        thread = new Thread(
                new Runnable(){
                    @Override
                    public void run() {
                        for (NetworkDataSource source : sources) {
                            download(source, lat, lon, alt,getBaseContext());
                        }
                    }
                }
        );
        thread.start();
    }

    private boolean download(NetworkDataSource source, double lat, double lon, double alt, Context context) {
        if (source==null) return false;

        if (source instanceof GasolinatorDataSource) {
            GasolinatorDataSource gasolinatorDataSource = GasolinatorDataSource.getInstance(this);

            final List<Marker> gasolinatorMarkers = gasolinatorDataSource.getGasolinatorMarkers();
            if (gasolinatorMarkers!=null) {
                String name = ((GasolinatorMarker)gasolinatorMarkers.get(0)).getStation().getName();
                Log.i("Gasolinator Maker detected ====:", name);
                final List<Marker> gasolinatorMarkersFilteredByPrefs = gasolinatorDataSource.getGasolinatorMarkersFilteredByPrefs(this);
                ARData.addMarkers(gasolinatorMarkersFilteredByPrefs);
                return true;
            }
        }
//            GasolinatorDataSource gasolinatorDataSource = GasolinatorDataSource.getInstance(context);
//            gasolinatorDataSource.refresh(this);
//            final List<Marker> gasolinatorDataSourceMarkers = gasolinatorDataSource.getMarkers();
//            if (gasolinatorDataSourceMarkers!=null) {
//                ARData.addMarkers(gasolinatorDataSourceMarkers);
//                return true;
//            }
//            return false;
//        }

        String url = null;
        try {
//            final float radius = ARData.getRadius();
            GasolinatorPreferences gasolinatorPreferences = new GasolinatorPreferences(context);
            final float radius = gasolinatorPreferences.getRadius();
            url = source.createRequestURL(lat, lon, alt, radius, locale);
        } catch (NullPointerException e) {
            return false;
        }

        List<Marker> markers = null;
        try {
            markers = source.parse(url);
        } catch (NullPointerException e) {
            return false;
        }

        ARData.addMarkers(markers);
        return true;
    }
}
